package com.example.javademo;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class MyAdataer extends BaseAdapter {
    private List<Msg> list;
    private Context context;

    public MyAdataer(List<Msg> list, Context context){
        this.list = list;
        this.context = context;
    }

    /*
    * 返回数据项总数（列表长度）
    * */
    @Override
    public int getCount(){
        return list.size();
    }


    /*
    * 获取指定位置的数据对象
    * */
    @Override
    public Object getItem(int position){
        return null;
    }

    /*
    * 获取数据项的唯一ID（通常返回position）
    * */
    @Override
    public long getItemId(int position){
        return 0;
    }

    /*
    * 核心方法：创建/复用视图并绑定数据
    * position: 索引值
    * convertView: 视图自身
    * parent: 父布局
    * */
    @Override
    public View getView(int position, View view, ViewGroup parent){
        ViewHolder holder;

        if(view == null){
            Log.d("TAG", "getView: "+position);
            view = LayoutInflater.from(context).inflate(R.layout.base_item, null);
            holder = new ViewHolder();
            holder.profile = (ImageView) view.findViewById(R.id.profie);
            holder.nickname = (TextView) view.findViewById(R.id.nikeName);
            holder.content = (TextView) view.findViewById(R.id.base_content);
            holder.like = (Button) view.findViewById(R.id.base_like);
            // 关键：将ViewHolder存储到view的tag中
            view.setTag(holder);
        } else {
            // 关键：从已存在的view中获取ViewHolder
            holder = (ViewHolder) view.getTag();
        }

        // 设置数据
        holder.profile.setImageResource(list.get(position).getProfile());
        holder.nickname.setText(list.get(position).getNickname());
        holder.content.setText(list.get(position).getBaseContent());
        holder.like.setText(list.get(position).isLike() ? "取消点赞" : "点赞");

        return view;
    }
//    避免重复查找：不需要每次都调用 findViewById
    static class  ViewHolder{
        public ImageView profile;
        public TextView nickname;
        public TextView content;
        public Button like;
    }

}
